package com.example.palette.fragment;


import static com.example.palette.bean.FileDetected.FILE_TYPE_DIRECTORY;
import static com.example.palette.bean.FileDetected.FILE_TYPE_UNKNOWN;

import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.example.palette.R;
import com.example.palette.adapter.BaseAdapter;
import com.example.palette.adapter.DirAdapter;
import com.example.palette.adapter.FileAdapter;
import com.example.palette.bean.FileDetected;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FileSelectDialogFragment extends DialogFragment {

    private String mOriginDestFileAbsolutePath;
    private List<FileDetected> mDirLevelList = new ArrayList<>();
    private List<FileDetected> mFileDetailList = new ArrayList<>();
    DirAdapter mDirAdapter;
    FileAdapter mFileAdapter;
    TextView tv_empty;
    RecyclerView rv_fileDetail;
    private String mSelectedFilePath;
    public FileSelectDialogFragment(String originDestFileAbsolutePath) {
        mOriginDestFileAbsolutePath = originDestFileAbsolutePath;
    }

    private void fillDirLevel(String filePath) {
        if(TextUtils.isEmpty(filePath)){
           throw new NullPointerException("dest file path can not be null");
        }else {
            File current = new File(filePath);
            // /sdcard/download/image
            if(current.exists()){
                String[] split = filePath.split("/");
                mDirLevelList.clear();
                for(String string:split){
                    if(TextUtils.isEmpty(string)){
                        continue;
//                        FileDetected fileDetected = new FileDetected();
//                        fileDetected.setName("/");
//                        fileDetected.setFileType(FILE_TYPE_DIRECTORY);
//                        mDirLevelList.add(fileDetected);
                    }else {
                        String substring = filePath.substring(0, filePath.lastIndexOf(string) + string.length());
                        FileDetected fileDetected = new FileDetected();
                        fileDetected.setName(string);
                        fileDetected.setFileType(new File(substring).isDirectory() ? FILE_TYPE_DIRECTORY : FILE_TYPE_UNKNOWN);
                        mDirLevelList.add(fileDetected);
                    }
                }
//                if(mDirLevelList.isEmpty()){
//                    FileDetected fileDetected = new FileDetected();
//                    fileDetected.setName("/");
//                    fileDetected.setFileType(FILE_TYPE_DIRECTORY);
//                    mDirLevelList.add(fileDetected);
//                }
                fillFileDetail();
            }else {
                throw new NullPointerException("dest file path not existed");
            }
        }
    }

    private void fillFileDetail(){
        mSelectedFilePath = null;
        mFileDetailList.clear();
        StringBuilder stringBuilder = new StringBuilder();
        for(FileDetected fileDetected:mDirLevelList){
            String name = fileDetected.getName();
            if("/".equals(name)){
                stringBuilder.append(name);
            }else {
                stringBuilder.append(name);
                stringBuilder.append("/");
            }
        }
        String currentPath = stringBuilder.toString().substring(0, stringBuilder.length() - 1);
        File file = new File(currentPath);
        if(file.isDirectory()){
            File[] files = file.listFiles();
            if(files != null){
                for(File f: files){
                    FileDetected fileDetected = new FileDetected();
                    if(f.isDirectory()){
                        fileDetected.setFileType(FILE_TYPE_DIRECTORY);
                    }else {
                        fileDetected.setFileType(FILE_TYPE_UNKNOWN);
                    }
                    fileDetected.setName(f.getAbsolutePath());
                    mFileDetailList.add(fileDetected);
                }
                Collections.sort(mFileDetailList);
            }
        }
        mDirAdapter.notifyDataSetChanged();
        mFileAdapter.notifyDataSetChanged();
        if(mFileDetailList.isEmpty()){
            rv_fileDetail.setVisibility(View.GONE);
            tv_empty.setVisibility(View.VISIBLE);
        }else {
            rv_fileDetail.setVisibility(View.VISIBLE);
            tv_empty.setVisibility(View.GONE);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NO_FRAME,R.style.DialogFragmentNoPaddingStyle);
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if(dialog != null){
            Window window = dialog.getWindow();
            if(window != null){
                window.setBackgroundDrawableResource(R.drawable.bg_white_rectangle);
                window.setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.MATCH_PARENT);
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        setCancelable(false);
        View root = inflater.inflate(R.layout.dialog_file_select, container);
        RecyclerView rv_filePath = root.findViewById(R.id.rv_filePath);
        rv_fileDetail = root.findViewById(R.id.rv_fileDetail);
        tv_empty = root.findViewById(R.id.tv_empty);
        TextView tv_cancel = root.findViewById(R.id.tv_cancel);
        TextView tv_confirm = root.findViewById(R.id.tv_confirm);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getContext(),mSelectedFilePath==null?"未选择":mSelectedFilePath,Toast.LENGTH_SHORT).show();
            }
        });
        rv_filePath.setLayoutManager(new LinearLayoutManager(getContext(),RecyclerView.HORIZONTAL,false));
        mDirAdapter = new DirAdapter(R.layout.rv_dir_item,mDirLevelList);
        mDirAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener<FileDetected>() {
            @Override
            public void onItemClick(FileDetected fileDetected, int position,int viewId) {
//                if("/".equals(fileDetected.getName())){
//                    fillDirLevel(mOriginDestFileAbsolutePath);
//                    return;
//                }
                List<FileDetected> temp = new ArrayList<>();
                for (int i = 0; i <= position; i++) {
                    FileDetected item = mDirLevelList.get(i);
                    FileDetected detected = new FileDetected();
                    detected.setName(item.getName());
                    detected.setFileType(item.getFileType());
                    temp.add(detected);
                }
                mDirLevelList.clear();
                mDirLevelList.addAll(temp);
                fillFileDetail();
            }
        });
        rv_filePath.setAdapter(mDirAdapter);
        rv_fileDetail.setLayoutManager(new LinearLayoutManager(getContext()));
        mFileAdapter = new FileAdapter(R.layout.rv_file_item,mFileDetailList);
        mFileAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener<FileDetected>() {
            @Override
            public void onItemClick(FileDetected fileDetected, int position,int viewId) {
                if(fileDetected == null){
                    if(mFileDetailList.get(position).isSelected()){
                        mSelectedFilePath = null;
                        mFileDetailList.get(position).setSelected(false);
                        mFileAdapter.notifyItemChanged(position);
                    }else {
                        for(FileDetected f:mFileDetailList){
                            f.setSelected(false);
                        }
                        mSelectedFilePath = mFileDetailList.get(position).getName();
                        mFileDetailList.get(position).setSelected(true);
                        mFileAdapter.notifyDataSetChanged();
                    }
                }else {
                    if(fileDetected.getFileType() == FILE_TYPE_DIRECTORY){
                        fillDirLevel(fileDetected.getName());
                    }
                }
            }
        });
        rv_fileDetail.setAdapter(mFileAdapter);
        fillDirLevel(mOriginDestFileAbsolutePath);
        return root;
    }

    public void show(FragmentActivity fragmentActivity) {
        if (!isResumed()) {
            super.showNow(fragmentActivity.getSupportFragmentManager(), "FileSelectDialogFragment");
        }
    }
}
